﻿<template>
  <div>
    <el-card
      class="card-item"
      shadow="hover"
      @contextmenu.prevent="onContextmenu($event, cardItem)"
    >
      <template v-if="cardItem.title" #header>
        <div class="card-header flex justify-between items-center">
          <span>{{ cardItem.title }}</span>
          <el-tooltip
            :show-after="500"
            :content="cardItem.connected ? '已连接' : '未连接'"
            placement="bottom"
            effect="light"
          >
            <el-icon :class="cardItem.connected ? 'text-green-500' : 'text-red-500'" class="ml-2">
              <Connection />
            </el-icon>
          </el-tooltip>
        </div>
      </template>
      <div class="card-content">
        <el-text
          v-if="!cardItem.props || cardItem.props.length === 0"
          class="flex justify-center w-full"
        >
          暂无数据
        </el-text>
        <el-descriptions :column="1" border>
          <el-descriptions-item v-for="p in cardItem.props" :key="p.propName">
            <template #label>
              {{ p.propName }}
            </template>
            <el-text truncated style="max-width: 150px">{{ p.propValue }}</el-text>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
    <AgelContextMenu
      v-model="contextMenu.show"
      :x="contextMenu.x"
      :y="contextMenu.y"
      :menus="contextMenu.data"
      @select="contextMenu.onSelect"
    />
  </div>

  <!-- 配置详情弹窗 -->
  <el-dialog v-if="dialogDetailVisible" v-model="dialogDetailVisible" width="700" title="设备修改">
    <DeviceDetail :form-data="dialogDetailData" @close="handleCloseDialog" />
  </el-dialog>
  <!-- 配置详情弹窗 End -->
</template>

<script setup lang="ts">
import { Connection } from "@element-plus/icons-vue";
import DeviceAPI from "@/api/business/device.api";
import deviceApi from "@/api/business/device.api";
import DeviceDetail from "@/views/business/devices/components/DeviceDetail.vue";
import { SignalrToken } from "@/enums/business/signalrToken.enum";
import { useSignalRStore } from "@/store/modules/signalr.store";

const prop = defineProps<{
  cardItem: CardItem;
}>();

// region signalr

const signalrStore = useSignalRStore();
onMounted(() => {
  signalrStore.subscribe(
    SignalrToken.DeviceConnectStatus,
    (deviceId: number, isConnected: boolean) => {
      if (deviceId !== prop.cardItem.id) return;
      prop.cardItem.connected = isConnected;
    }
  );
  signalrStore.subscribe(SignalrToken.DeviceVals, (deviceId: number, deviceVals: any) => {
    // console.log("deviceVals", deviceId, deviceVals);
    if (prop.cardItem.id != deviceId) return;
    prop.cardItem.props.length = 0;
    Object.keys(deviceVals).forEach((key) => {
      prop.cardItem.props.push({
        propName: key,
        propValue: deviceVals[key],
      });
    });
  });
});

// endregion

// region 右键菜单

const MENU_NAME = {
  Config: "设备配置",
  Connect: "连接",
  Disconnect: "断开",
};

const contextMenu = reactive({
  device: {},
  show: false,
  x: 0,
  y: 0,
  data: [],
  onSelect: (item: any) => {
    console.log(item);
    if (prop.cardItem) {
      // 根据当前设备状态执行不同操作
      if (item.title === MENU_NAME.Connect) {
        // 执行连接操作
        DeviceAPI.connect(prop.cardItem.id).then(() => {
          ElMessage.success(`${prop.cardItem.title}连接成功`);
        });
      } else if (item.title === MENU_NAME.Disconnect) {
        // 执行断开操作
        DeviceAPI.disconnect(prop.cardItem.id).then(() => {
          ElMessage.success(`${prop.cardItem.title}已断开连接`);
        });
      } else if (item.title === MENU_NAME.Config) {
        // 打开设置页
        handleOpenDialog(prop.cardItem.id);
      }
    }
  },
});

function onContextmenu(e: MouseEvent, device: CardItem) {
  // 根据设备连接状态动态生成菜单项
  contextMenu.data = [
    { title: MENU_NAME.Config, icon: "Setting" },
    { title: device.connected ? MENU_NAME.Disconnect : MENU_NAME.Connect, icon: "Connection" },
  ];

  contextMenu.show = true;
  contextMenu.x = e.clientX;
  contextMenu.y = e.clientY;
  e.preventDefault();

  // 等待后关闭菜单
  setTimeout(() => {
    contextMenu.show = false;
  }, 1000 * 5);
}

// endregion

// region 设备参数弹窗

const dialogDetailVisible = ref(false);
const dialogDetailData = ref<DeviceConfig>();

function handleOpenDialog(id: number) {
  deviceApi.getDeviceConfig(id).then((res) => {
    dialogDetailData.value = res;
    dialogDetailVisible.value = true;
  });
}
function handleCloseDialog() {
  dialogDetailVisible.value = false;
}

// endregion
</script>

<style scoped lang="scss">
:deep(.el-card__header) {
  padding: 10px;
}
:deep(.el-card__body) {
  padding: 10px;
}

.card-item {
  margin-bottom: 10px;
  flex-shrink: 0;
}

.card-header {
  font-weight: 600;
}

.card-content {
  line-height: 1.6;
}
</style>
